package com.yfbao.horizon.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils_C3P0 {
    //4.提升作用域
    private static ComboPooledDataSource dataSource = null;

    //1.获取数据源 dataSource
    static {
        try {
            //创建数据源 (直接new一个ComboPooledDataSource()对象就可以获得数据源)
            dataSource = new ComboPooledDataSource();           //C3P0的缺省(默认)配置
            //ComboPooledDataSource dataSource = new ComboPooledDataSource("MySQL");  //C3P0的命名配置（配置文件写法）

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.获取连接 (数据源dataSource自带连接)
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //3.释放连接资源
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
